import tkinter as tk
from tkinter import ttk, messagebox, filedialog
import json
import os
from pypinyin import lazy_pinyin, Style
import threading
import time
from tkinter import font
from enhanced_styles import EnhancedPoetryDisplay, StyleManager, RoundedFrame
import colorsys

class EnhancedPoetryReader:
    def __init__(self, root):
        self.root = root
        self.root.title("古诗词跟读器 - 增强版")
        self.root.geometry("1000x700")
        
        # 增强版设置
        self.settings = {
            "font_family": "Microsoft YaHei",
            "font_size": 28,
            "text_color": "#2C3E50",
            "highlight_color": "#E74C3C",
            "bg_color": "#F8F9FA",
            "bg_image": None,
            "bg_pattern": "solid",  # solid, grid, gradient
            "reading_speed": 1.0,
            "window_opacity": 0.95,
            "show_pinyin": True,
            "corner_radius": 25,
            "theme": "default",
            "animation_type": "character",  # character, word, line
            "enable_shadow": True,
            "shadow_color": "#000000",
            "shadow_offset": 2
        }
        
        # 诗词数据库
        self.poetry_database = [
            {
                "title": "静夜思",
                "author": "李白",
                "dynasty": "唐",
                "content": [
                    "床前明月光",
                    "疑是地上霜",
                    "举头望明月",
                    "低头思故乡"
                ]
            },
            {
                "title": "春晓",
                "author": "孟浩然",
                "dynasty": "唐",
                "content": [
                    "春眠不觉晓",
                    "处处闻啼鸟",
                    "夜来风雨声",
                    "花落知多少"
                ]
            },
            {
                "title": "登鹳雀楼",
                "author": "王之涣",
                "dynasty": "唐",
                "content": [
                    "白日依山尽",
                    "黄河入海流",
                    "欲穷千里目",
                    "更上一层楼"
                ]
            },
            {
                "title": "相思",
                "author": "王维",
                "dynasty": "唐",
                "content": [
                    "红豆生南国",
                    "春来发几枝",
                    "愿君多采撷",
                    "此物最相思"
                ]
            }
        ]
        
        self.current_poetry_index = 0
        self.current_poetry = self.poetry_database[self.current_poetry_index]
        
        # 跟读状态
        self.is_reading = False
        self.current_line = 0
        self.current_char = 0
        self.animation_thread = None
        
        # 样式管理器
        self.style_manager = StyleManager()
        
        self.setup_ui()
        self.apply_theme(self.settings["theme"])
        
    def setup_ui(self):
        """设置界面"""
        # 设置窗口透明度
        self.root.attributes('-alpha', self.settings["window_opacity"])
        
        # 创建主容器
        self.main_container = ttk.Frame(self.root)
        self.main_container.pack(fill=tk.BOTH, expand=True)
        
        # 创建顶部工具栏
        self.create_toolbar()
        
        # 创建诗词显示区域
        self.create_poetry_display()
        
        # 创建控制面板
        self.create_control_panel()
        
        # 创建状态栏
        self.create_status_bar()
        
        # 设置样式
        self.setup_styles()
        
    def create_toolbar(self):
        """创建工具栏"""
        toolbar = ttk.Frame(self.main_container)
        toolbar.pack(fill=tk.X, padx=10, pady=5)
        
        # 诗词选择
        ttk.Label(toolbar, text="选择诗词:").pack(side=tk.LEFT, padx=5)
        
        poetry_names = [f"{poem['title']} - {poem['author']}" for poem in self.poetry_database]
        self.poetry_var = tk.StringVar(value=poetry_names[self.current_poetry_index])
        self.poetry_combo = ttk.Combobox(toolbar, textvariable=self.poetry_var, values=poetry_names, width=30)
        self.poetry_combo.pack(side=tk.LEFT, padx=5)
        self.poetry_combo.bind('<<ComboboxSelected>>', self.on_poetry_selected)
        
        # 主题选择
        ttk.Label(toolbar, text="主题:").pack(side=tk.LEFT, padx=(20, 5))
        
        theme_names = self.style_manager.get_available_themes()
        self.theme_var = tk.StringVar(value=self.settings["theme"])
        self.theme_combo = ttk.Combobox(toolbar, textvariable=self.theme_var, values=theme_names, width=15)
        self.theme_combo.pack(side=tk.LEFT, padx=5)
        self.theme_combo.bind('<<ComboboxSelected>>', self.on_theme_selected)
        
        # 背景模式
        ttk.Label(toolbar, text="背景:").pack(side=tk.LEFT, padx=(20, 5))
        
        bg_modes = ["solid", "grid", "gradient", "image"]
        self.bg_var = tk.StringVar(value=self.settings["bg_pattern"])
        self.bg_combo = ttk.Combobox(toolbar, textvariable=self.bg_var, values=bg_modes, width=10)
        self.bg_combo.pack(side=tk.LEFT, padx=5)
        self.bg_combo.bind('<<ComboboxSelected>>', self.on_bg_mode_selected)
        
    def create_poetry_display(self):
        """创建诗词显示区域"""
        # 创建显示容器
        self.display_frame = ttk.Frame(self.main_container)
        self.display_frame.pack(fill=tk.BOTH, expand=True, padx=20, pady=10)
        
        # 创建画布用于高级效果
        self.display_canvas = tk.Canvas(
            self.display_frame,
            bg=self.settings["bg_color"],
            highlightthickness=0
        )
        self.display_canvas.pack(fill=tk.BOTH, expand=True)
        
        # 创建诗词文本显示
        self.create_poetry_text()
        
        # 绑定大小变化事件
        self.display_canvas.bind("<Configure>", self.on_display_resize)
        
    def create_poetry_text(self):
        """创建诗词文本显示"""
        # 标题显示
        title_text = f"{self.current_poetry['title']}"
        author_text = f"{self.current_poetry['dynasty']} · {self.current_poetry['author']}"
        
        # 计算居中位置
        self.display_canvas.update_idletasks()
        canvas_width = self.display_canvas.winfo_width()
        canvas_height = self.display_canvas.winfo_height()
        
        if canvas_width > 1 and canvas_height > 1:
            # 标题
            title_x = canvas_width // 2
            title_y = canvas_height // 6
            
            self.title_id = self.display_canvas.create_text(
                title_x, title_y,
                text=title_text,
                font=(self.settings["font_family"], self.settings["font_size"] + 12, "bold"),
                fill=self.settings["text_color"],
                tags="title"
            )
            
            # 作者
            author_x = canvas_width // 2
            author_y = title_y + 60
            
            self.author_id = self.display_canvas.create_text(
                author_x, author_y,
                text=author_text,
                font=(self.settings["font_family"], self.settings["font_size"] - 4),
                fill=self.settings["text_color"],
                tags="author"
            )
            
            # 诗词内容
            self.line_ids = []
            self.pinyin_ids = []
            
            start_y = author_y + 80
            line_spacing = 80
            pinyin_offset = 35  # 拼音与诗句的垂直间距
            
            for i, line in enumerate(self.current_poetry["content"]):
                line_y = start_y + i * line_spacing
                
                # 拼音（先显示在上方）
                if self.settings["show_pinyin"]:
                    # 获取逐字拼音并计算位置
                    pinyin_list = lazy_pinyin(line, style=Style.TONE)
                    chars = list(line)
                    
                    # 计算每个字符的宽度来对齐拼音
                    total_width = 0
                    char_widths = []
                    
                    # 计算每个字符的宽度
                    for char in chars:
                        bbox = self.display_canvas.bbox(self.display_canvas.create_text(
                            0, 0, text=char, font=(self.settings["font_family"], self.settings["font_size"]),
                            state='hidden'  # 临时创建隐藏文本来测量
                        ))
                        if bbox:
                            width = bbox[2] - bbox[0]
                            char_widths.append(width)
                            total_width += width
                        else:
                            char_widths.append(20)  # 默认宽度
                            total_width += 20
                    
                    # 创建对齐的拼音文本
                    aligned_pinyin = ""
                    for j, (char, pinyin) in enumerate(zip(chars, pinyin_list)):
                        # 计算拼音需要的空格数来对齐对应的汉字
                        pinyin_length = len(pinyin)
                        char_width = char_widths[j] if j < len(char_widths) else 20
                        
                        # 简单对齐：在拼音前后添加空格
                        spaces_needed = max(0, (char_width // 10) - pinyin_length)
                        left_spaces = spaces_needed // 2
                        right_spaces = spaces_needed - left_spaces
                        
                        aligned_pinyin += " " * left_spaces + pinyin + " " * right_spaces + "  "
                    
                    pinyin_y = line_y - pinyin_offset  # 拼音在诗句上方
                    
                    pinyin_id = self.display_canvas.create_text(
                        canvas_width // 2, pinyin_y,
                        text=aligned_pinyin.strip(),
                        font=(self.settings["font_family"], self.settings["font_size"] - 8),
                        fill=self.settings["text_color"],
                        tags=f"pinyin_{i}"
                    )
                    self.pinyin_ids.append(pinyin_id)
                
                # 诗句（后显示，确保在拼音下方）
                line_id = self.display_canvas.create_text(
                    canvas_width // 2, line_y,
                    text=line,
                    font=(self.settings["font_family"], self.settings["font_size"]),
                    fill=self.settings["text_color"],
                    tags=f"line_{i}"
                )
                self.line_ids.append(line_id)
    
    def create_control_panel(self):
        """创建控制面板"""
        control_frame = ttk.Frame(self.main_container)
        control_frame.pack(fill=tk.X, padx=20, pady=10)
        
        # 左侧控制按钮
        left_controls = ttk.Frame(control_frame)
        left_controls.pack(side=tk.LEFT)
        
        self.start_btn = ttk.Button(
            left_controls,
            text="▶ 开始跟读",
            command=self.start_reading,
            style="Control.TButton"
        )
        self.start_btn.pack(side=tk.LEFT, padx=5)
        
        self.stop_btn = ttk.Button(
            left_controls,
            text="⏹ 停止跟读",
            command=self.stop_reading,
            state=tk.DISABLED,
            style="Control.TButton"
        )
        self.stop_btn.pack(side=tk.LEFT, padx=5)
        
        self.pause_btn = ttk.Button(
            left_controls,
            text="⏸ 暂停",
            command=self.pause_reading,
            state=tk.DISABLED,
            style="Control.TButton"
        )
        self.pause_btn.pack(side=tk.LEFT, padx=5)
        
        # 中间速度控制
        center_controls = ttk.Frame(control_frame)
        center_controls.pack(side=tk.LEFT, padx=(50, 0))
        
        ttk.Label(center_controls, text="跟读速度:").pack(side=tk.LEFT)
        
        self.speed_scale = ttk.Scale(
            center_controls,
            from_=0.3,
            to=2.5,
            value=self.settings["reading_speed"],
            command=self.on_speed_changed,
            length=200
        )
        self.speed_scale.pack(side=tk.LEFT, padx=10)
        
        self.speed_label = ttk.Label(center_controls, text=f"{self.settings['reading_speed']:.1f}x")
        self.speed_label.pack(side=tk.LEFT)
        
        # 右侧高级设置
        right_controls = ttk.Frame(control_frame)
        right_controls.pack(side=tk.RIGHT)
        
        self.settings_btn = ttk.Button(
            right_controls,
            text="⚙ 高级设置",
            command=self.open_advanced_settings,
            style="Control.TButton"
        )
        self.settings_btn.pack(side=tk.LEFT, padx=5)
        
        self.fullscreen_btn = ttk.Button(
            right_controls,
            text="⛶ 全屏",
            command=self.toggle_fullscreen,
            style="Control.TButton"
        )
        self.fullscreen_btn.pack(side=tk.LEFT, padx=5)
        
    def create_status_bar(self):
        """创建状态栏"""
        status_frame = ttk.Frame(self.main_container)
        status_frame.pack(fill=tk.X, padx=20, pady=5)
        
        self.status_label = ttk.Label(status_frame, text="就绪")
        self.status_label.pack(side=tk.LEFT)
        
        self.progress_label = ttk.Label(status_frame, text="")
        self.progress_label.pack(side=tk.RIGHT)
        
    def setup_styles(self):
        """设置样式"""
        style = ttk.Style()
        
        # 配置按钮样式
        style.configure(
            "Control.TButton",
            padding=10,
            font=(self.settings["font_family"], 12)
        )
        
        # 配置滑块样式
        style.configure(
            "TScale",
            sliderthickness=20,
            sliderlength=30
        )
        
    def apply_theme(self, theme_name):
        """应用主题"""
        theme = self.style_manager.get_theme(theme_name)
        self.settings.update(theme)
        
        # 更新背景
        self.update_background()
        
        # 更新文本颜色
        self.update_text_colors()
        
    def update_background(self):
        """更新背景"""
        bg_pattern = self.settings.get("bg_pattern", "solid")
        
        if bg_pattern == "image" and self.settings.get("bg_image"):
            self.set_background_image()
        elif bg_pattern == "grid":
            self.set_grid_background()
        elif bg_pattern == "gradient":
            self.set_gradient_background()
        else:
            self.set_solid_background()
            
    def set_solid_background(self):
        """设置纯色背景"""
        self.display_canvas.config(bg=self.settings["bg_color"])
        
    def set_grid_background(self):
        """设置栅格背景"""
        # 这里可以实现栅格背景
        self.display_canvas.config(bg=self.settings["bg_color"])
        
    def set_gradient_background(self):
        """设置渐变背景"""
        # 这里可以实现渐变背景
        self.display_canvas.config(bg=self.settings["bg_color"])
        
    def set_background_image(self):
        """设置背景图片"""
        # 这里可以实现背景图片
        self.display_canvas.config(bg=self.settings["bg_color"])
        
    def update_text_colors(self):
        """更新文本颜色"""
        # 更新标题
        if hasattr(self, 'title_id'):
            self.display_canvas.itemconfig(self.title_id, fill=self.settings["text_color"])
        
        # 更新作者
        if hasattr(self, 'author_id'):
            self.display_canvas.itemconfig(self.author_id, fill=self.settings["text_color"])
        
        # 更新诗句 - 检查line_ids是否存在
        if hasattr(self, 'line_ids'):
            for line_id in self.line_ids:
                self.display_canvas.itemconfig(line_id, fill=self.settings["text_color"])
        
        # 更新拼音 - 检查pinyin_ids是否存在
        if hasattr(self, 'pinyin_ids'):
            for pinyin_id in self.pinyin_ids:
                self.display_canvas.itemconfig(pinyin_id, fill=self.settings["text_color"])
            
    def on_display_resize(self, event):
        """处理显示区域大小变化"""
        # 重新创建文本显示
        self.display_canvas.delete("all")
        self.create_poetry_text()
        
    def on_poetry_selected(self, event):
        """处理诗词选择"""
        selected_index = self.poetry_combo.current()
        if selected_index >= 0:
            self.current_poetry_index = selected_index
            self.current_poetry = self.poetry_database[selected_index]
            self.display_canvas.delete("all")
            self.create_poetry_text()
            
    def on_theme_selected(self, event):
        """处理主题选择"""
        selected_theme = self.theme_combo.get()
        self.apply_theme(selected_theme)
        
    def on_bg_mode_selected(self, event):
        """处理背景模式选择"""
        selected_mode = self.bg_combo.get()
        self.settings["bg_pattern"] = selected_mode
        self.update_background()
        
    def on_speed_changed(self, value):
        """处理速度变化"""
        speed = float(value)
        self.settings["reading_speed"] = speed
        self.speed_label.config(text=f"{speed:.1f}x")
        
    def start_reading(self):
        """开始跟读"""
        if not self.is_reading:
            self.is_reading = True
            self.start_btn.config(state=tk.DISABLED)
            self.stop_btn.config(state=tk.NORMAL)
            self.pause_btn.config(state=tk.NORMAL)
            
            # 重置位置
            self.current_line = 0
            self.current_char = 0
            
            # 重置所有文本颜色
            self.reset_text_colors()
            
            # 创建跟读线程
            self.animation_thread = threading.Thread(target=self.reading_animation)
            self.animation_thread.daemon = True
            self.animation_thread.start()
            
            self.status_label.config(text="正在跟读...")
            
    def stop_reading(self):
        """停止跟读"""
        self.is_reading = False
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.pause_btn.config(state=tk.DISABLED)
        
        # 重置所有文本颜色
        self.reset_text_colors()
        
        self.status_label.config(text="就绪")
        
    def pause_reading(self):
        """暂停跟读"""
        self.is_reading = not self.is_reading
        if self.is_reading:
            self.pause_btn.config(text="⏸ 暂停")
            self.status_label.config(text="正在跟读...")
            # 继续动画
            self.animation_thread = threading.Thread(target=self.reading_animation)
            self.animation_thread.daemon = True
            self.animation_thread.start()
        else:
            self.pause_btn.config(text="▶ 继续")
            self.status_label.config(text="已暂停")
            
    def reading_animation(self):
        """跟读动画"""
        try:
            animation_type = self.settings["animation_type"]
            
            if animation_type == "character":
                self.character_by_character_animation()
            elif animation_type == "word":
                self.word_by_word_animation()
            elif animation_type == "line":
                self.line_by_line_animation()
                
        except Exception as e:
            self.root.after(0, lambda: messagebox.showerror("错误", f"动画过程中出现错误: {str(e)}"))
            
    def character_by_character_animation(self):
        """逐字符动画"""
        for line_idx, line in enumerate(self.current_poetry["content"]):
            if not self.is_reading:
                break
            
            self.current_line = line_idx
            chars = list(line)
            
            for char_idx, char in enumerate(chars):
                if not self.is_reading:
                    break
                
                self.current_char = char_idx
                
                # 更新UI（高亮到当前字符）
                self.root.after(0, self.highlight_to_character, line_idx, char_idx)
                
                # 根据速度等待
                time.sleep(0.4 / self.settings["reading_speed"])
            
            # 行结束，标记整行为完成
            if self.is_reading:
                self.root.after(0, self.highlight_line_completed, line_idx)
                time.sleep(0.8 / self.settings["reading_speed"])
        
        # 跟读完成
        if self.is_reading:
            self.root.after(0, self.reading_completed)
            
    def word_by_word_animation(self):
        """逐词动画"""
        for line_idx, line in enumerate(self.current_poetry["content"]):
            if not self.is_reading:
                break
            
            words = line.split()
            
            for word_idx, word in enumerate(words):
                if not self.is_reading:
                    break
                
                # 高亮当前词
                self.root.after(0, self.highlight_word, line_idx, word_idx)
                
                time.sleep(0.6 / self.settings["reading_speed"])
            
            if self.is_reading:
                time.sleep(0.5 / self.settings["reading_speed"])
                
    def line_by_line_animation(self):
        """逐行动画"""
        for line_idx, line in enumerate(self.current_poetry["content"]):
            if not self.is_reading:
                break
            
            # 高亮当前行
            self.root.after(0, self.highlight_line, line_idx)
            
            # 计算行的朗读时间（基于字符数）
            char_count = len(line)
            line_time = (char_count * 0.3 + 1.0) / self.settings["reading_speed"]
            
            time.sleep(line_time)
            
    def highlight_to_character(self, line_idx, char_idx):
        """高亮到指定字符"""
        line = self.current_poetry["content"][line_idx]
        
        # 创建渐变效果
        highlighted_part = line[:char_idx + 1]
        remaining_part = line[char_idx + 1:]
        
        # 更新显示
        if line_idx < len(self.line_ids):
            self.display_canvas.itemconfig(
                self.line_ids[line_idx],
                text=line,
                fill=self.settings["highlight_color"]
            )
            
    def highlight_line(self, line_idx):
        """高亮整行"""
        if line_idx < len(self.line_ids):
            self.display_canvas.itemconfig(
                self.line_ids[line_idx],
                fill=self.settings["highlight_color"]
            )
            
    def highlight_word(self, line_idx, word_idx):
        """高亮词语"""
        # 这里可以实现词语高亮逻辑
        if line_idx < len(self.line_ids):
            self.display_canvas.itemconfig(
                self.line_ids[line_idx],
                fill=self.settings["highlight_color"]
            )
            
    def highlight_line_completed(self, line_idx):
        """标记行完成"""
        if line_idx < len(self.line_ids):
            self.display_canvas.itemconfig(
                self.line_ids[line_idx],
                fill=self.settings["highlight_color"]
            )
            
    def reset_text_colors(self):
        """重置文本颜色"""
        # 重置所有诗句颜色
        for line_id in self.line_ids:
            self.display_canvas.itemconfig(line_id, fill=self.settings["text_color"])
            
    def reading_completed(self):
        """跟读完成"""
        self.is_reading = False
        self.start_btn.config(state=tk.NORMAL)
        self.stop_btn.config(state=tk.DISABLED)
        self.pause_btn.config(state=tk.DISABLED)
        self.pause_btn.config(text="⏸ 暂停")
        
        self.status_label.config(text="跟读完成！")
        
        # 显示完成提示
        self.root.after(2000, lambda: self.status_label.config(text="就绪"))
        
    def open_advanced_settings(self):
        """打开高级设置"""
        settings_window = tk.Toplevel(self.root)
        settings_window.title("高级设置")
        
        # 设置窗口大小
        window_width = 500
        window_height = 600
        
        # 获取屏幕尺寸
        screen_width = settings_window.winfo_screenwidth()
        screen_height = settings_window.winfo_screenheight()
        
        # 计算居中位置
        x = (screen_width - window_width) // 2
        y = (screen_height - window_height) // 2
        
        # 设置窗口位置和大小
        settings_window.geometry(f"{window_width}x{window_height}+{x}+{y}")
        settings_window.transient(self.root)
        
        # 创建笔记本控件
        notebook = ttk.Notebook(settings_window)
        notebook.pack(fill=tk.BOTH, expand=True, padx=10, pady=10)
        
        # 外观设置页
        appearance_frame = ttk.Frame(notebook, padding=10)
        notebook.add(appearance_frame, text="外观设置")
        
        self.create_appearance_settings(appearance_frame)
        
        # 动画设置页
        animation_frame = ttk.Frame(notebook, padding=10)
        notebook.add(animation_frame, text="动画设置")
        
        self.create_animation_settings(animation_frame)
        
        # 关闭按钮
        close_btn = ttk.Button(settings_window, text="关闭", command=settings_window.destroy)
        close_btn.pack(pady=10)
        
    def create_appearance_settings(self, parent):
        """创建外观设置"""
        # 字体设置
        font_frame = ttk.LabelFrame(parent, text="字体设置", padding=10)
        font_frame.pack(fill=tk.X, pady=5)
        
        ttk.Label(font_frame, text="字体:").grid(row=0, column=0, sticky=tk.W)
        self.font_combo = ttk.Combobox(font_frame, values=list(font.families()), width=20)
        self.font_combo.set(self.settings["font_family"])
        self.font_combo.grid(row=0, column=1, padx=5)
        
        ttk.Label(font_frame, text="字号:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.size_spin = ttk.Spinbox(font_frame, from_=16, to=48, width=10)
        self.size_spin.set(self.settings["font_size"])
        self.size_spin.grid(row=1, column=1, padx=5)
        
        # 颜色设置
        color_frame = ttk.LabelFrame(parent, text="颜色设置", padding=10)
        color_frame.pack(fill=tk.X, pady=5)
        
        # 文字颜色
        ttk.Label(color_frame, text="文字颜色:").grid(row=0, column=0, sticky=tk.W, pady=5)
        self.text_color_btn = tk.Button(color_frame, bg=self.settings["text_color"], width=10, 
                                         command=lambda: self.choose_color("text_color"))
        self.text_color_btn.grid(row=0, column=1, padx=5)
        
        # 高亮颜色
        ttk.Label(color_frame, text="高亮颜色:").grid(row=1, column=0, sticky=tk.W, pady=5)
        self.highlight_color_btn = tk.Button(color_frame, bg=self.settings["highlight_color"], width=10,
                                           command=lambda: self.choose_color("highlight_color"))
        self.highlight_color_btn.grid(row=1, column=1, padx=5)
        
        # 背景颜色
        ttk.Label(color_frame, text="背景颜色:").grid(row=2, column=0, sticky=tk.W, pady=5)
        self.bg_color_btn = tk.Button(color_frame, bg=self.settings["bg_color"], width=10,
                                      command=lambda: self.choose_color("bg_color"))
        self.bg_color_btn.grid(row=2, column=1, padx=5)
        
        # 应用按钮
        apply_btn = ttk.Button(parent, text="应用设置", command=self.apply_appearance_settings)
        apply_btn.pack(pady=10)
        
    def create_animation_settings(self, parent):
        """创建动画设置"""
        # 动画类型
        anim_frame = ttk.LabelFrame(parent, text="动画类型", padding=10)
        anim_frame.pack(fill=tk.X, pady=5)
        
        anim_types = ["逐字符", "逐词", "逐行"]
        anim_values = ["character", "word", "line"]
        
        current_anim = self.settings["animation_type"]
        current_index = anim_values.index(current_anim) if current_anim in anim_values else 0
        
        self.anim_combo = ttk.Combobox(anim_frame, values=anim_types)
        self.anim_combo.current(current_index)
        self.anim_combo.pack(fill=tk.X)
        
        # 应用按钮
        apply_btn = ttk.Button(parent, text="应用设置", command=self.apply_animation_settings)
        apply_btn.pack(pady=10)
        
    def toggle_fullscreen(self):
        """切换全屏模式"""
        current_state = self.root.attributes('-fullscreen')
        self.root.attributes('-fullscreen', not current_state)
        
        if not current_state:
            self.fullscreen_btn.config(text="⛶ 退出全屏")
        else:
            self.fullscreen_btn.config(text="⛶ 全屏")
    
    def choose_color(self, color_type):
        """选择颜色"""
        # 这里简化处理，直接设置预设颜色
        colors = {
            "text_color": ["#2C3E50", "#34495E", "#1A252F"],
            "highlight_color": ["#E74C3C", "#C0392B", "#A93226"],
            "bg_color": ["#F8F9FA", "#ECF0F1", "#D5DBDB"]
        }
        
        current_colors = colors.get(color_type, ["#000000"])
        current_color = self.settings[color_type]
        
        # 循环到下一个颜色
        try:
            current_index = current_colors.index(current_color)
            next_index = (current_index + 1) % len(current_colors)
            new_color = current_colors[next_index]
        except ValueError:
            new_color = current_colors[0]
        
        self.settings[color_type] = new_color
        
        # 更新按钮颜色
        if color_type == "text_color":
            self.text_color_btn.config(bg=new_color)
        elif color_type == "highlight_color":
            self.highlight_color_btn.config(bg=new_color)
        elif color_type == "bg_color":
            self.bg_color_btn.config(bg=new_color)
    
    def apply_appearance_settings(self):
        """应用外观设置"""
        # 获取新设置
        new_font = self.font_combo.get()
        new_size = int(self.size_spin.get())
        
        # 更新设置
        self.settings["font_family"] = new_font
        self.settings["font_size"] = new_size
        
        # 重新创建文本显示
        self.display_canvas.delete("all")
        self.create_poetry_text()
        
        # 更新背景颜色
        self.update_background()
        
        messagebox.showinfo("设置", "外观设置已应用！")
    
    def apply_animation_settings(self):
        """应用动画设置"""
        anim_types = ["character", "word", "line"]
        anim_type_index = self.anim_combo.current()
        
        if 0 <= anim_type_index < len(anim_types):
            self.settings["animation_type"] = anim_types[anim_type_index]
            messagebox.showinfo("设置", f"动画类型已设置为：{self.anim_combo.get()}")
        else:
            messagebox.showwarning("设置", "请选择有效的动画类型！")
            
    def run(self):
        """运行应用"""
        self.root.mainloop()

def main():
    root = tk.Tk()
    app = EnhancedPoetryReader(root)
    app.run()

if __name__ == "__main__":
    main()